package com.newway.back.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.newway.back.entity.OrderRecord;
import com.newway.back.entity.Product;
import com.newway.back.mapper.OrderMapper;
import com.newway.back.mapper.ProductMapper;
import com.newway.common.context.UserInfo;
import com.newway.common.context.UserInfoContext;
import com.newway.common.exception.BusinessException;
import com.newway.common.result.Result;
import org.apache.commons.lang3.StringUtils;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.List;
import java.util.UUID;

@RestController
@RequestMapping("/system/order")
public class OrderController {

    @Resource
    OrderMapper orderMapper;

    @Resource
    ProductMapper productMapper;
    /**
     * 下单
     * @return
     */
    @PostMapping("/order")
    @Transactional
    public Result order(@RequestBody List<OrderRecord> list){
        UserInfo userInfo = UserInfoContext.getUserInfo();
        if(StringUtils.isBlank(userInfo.getAddress())||StringUtils.isBlank(userInfo.getAddress())){
            throw new BusinessException("请先去个人信息页面完善基本信息");
        }

        for(int i=0;i<list.size();i++){
            OrderRecord orderEntity = list.get(i);
            Product product = productMapper.selectById(orderEntity.getProductId());
            if(product==null){
                throw new BusinessException(product.getProductName() +":该产品已失效，请刷新后重试");
            }
            if(product.getBalanceCount()< orderEntity.getNum()){
                throw new BusinessException(product.getProductName() +":库存余额不足");
            }
            orderEntity.setUserId(UserInfoContext.getUserInfo().getId());
            orderEntity.setCreateTime(LocalDateTime.now());
            orderEntity.setStatus("1");
            orderEntity.setOrderNo(UUID.randomUUID().toString().replace("-",""));
            orderEntity.setAddress(userInfo.getAddress());
            orderEntity.setPhoneNo(userInfo.getPhoneNo());
            orderEntity.setUserName(userInfo.getUserName());
            orderMapper.insert(orderEntity);
            product.setBalanceCount(product.getBalanceCount()-orderEntity.getNum());
            product.setSoldCount(product.getSoldCount()+orderEntity.getNum());
            productMapper.updateById(product);
        }
        return Result.success();
    }

    @GetMapping("/list")
    public Result order(OrderRecord orderRecord){
        Page<OrderRecord> orderRecordPage = new Page<>(orderRecord.getPageNum(), orderRecord.getPageSize());
        QueryWrapper<OrderRecord> queryWrapper = new QueryWrapper<>();
        UserInfo userInfo = UserInfoContext.getUserInfo();
        if("wechat".equals(userInfo.getUserFrom())){
            queryWrapper.eq("user_id",userInfo.getId());
        }
        if(StringUtils.isNotBlank(orderRecord.getStatus())){
            queryWrapper.eq("status",orderRecord.getStatus());
        }
        queryWrapper.orderByDesc("create_time");
        Page<OrderRecord> result = orderMapper.selectPage(orderRecordPage, queryWrapper);
        return Result.success(result);
    }

    @PostMapping("/confirmOrder/{id}")
    public Result confirmOrder(@PathVariable("id")Integer id){
        OrderRecord orderRecord = orderMapper.selectById(id);
        if("1".equals(orderRecord.getStatus())){
            orderRecord.setStatus("3");
            orderMapper.updateById(orderRecord);
        }
       return Result.success();
    }

    @PostMapping("/cancelOrder/{id}")
    public Result cancelOrder(@PathVariable("id")Integer id){
        OrderRecord orderRecord = orderMapper.selectById(id);
        if("1".equals(orderRecord.getStatus())){
            orderRecord.setStatus("2");
            orderMapper.updateById(orderRecord);
            Product product = productMapper.selectById(orderRecord.getProductId());
            product.setBalanceCount(product.getBalanceCount()+orderRecord.getNum());
            product.setSoldCount(product.getSoldCount()-orderRecord.getNum());
            productMapper.updateById(product);
        }
        return Result.success();
    }
}
